import React, { Component } from 'react';
import { initTemplate, afterEvent, searchClick } from './events';
import presetVar from './presetVar';
import './index.less';
import { base, createPage, toast, promptBox } from 'nc-lightapp-front'
const { NCButton, NCModal } = base
import {
    ProfileStyle,
    ProfileBody,
    EmptyArea
} from 'src/erm/sscrppublic/common/components/profile';
import { setForm } from 'src/erm/sscrppublic/common/utils/setComponentUsed';
import requestApi from './requestApi';

class ExpenseaccountForPull extends Component {
    constructor(props) {
        super(props);
        setForm(props, presetVar.areaCode.searchArea)


        console.log('props===', props)
        let { form, button, table, editTable, search } = this.props;
        let { setSearchValue, setSearchValByField, getAllSearchData } = search;
        this.setSearchValByField = setSearchValByField;//设置查询区某个字段值
        this.getAllSearchData = getAllSearchData;//获取查询区所有字段数据


        initTemplate.call(this, props);
    }

    componentWillUnmount() {

    }
    selectArea = () => {
        let multiLang = this.props.MutiInit.getIntl(2011)
        let { getTradeType } = this.props;
        
        let relatedArr = window.presetVar.applicationForm_table ? window.presetVar.applicationForm_table : {}
        const that = this;
        return relatedArr.head && relatedArr.head.head[0] ? <NCButton
            colors="info"
            onClick={
                () => {
                    promptBox({
                        color: 'warning',
                        title: multiLang && multiLang.get('201103INUP-0045'),
                        content: multiLang && multiLang.get('201103INUP-0046'),
                        beSureBtnClick: () => {
                            console.log('this.props==', this.props)
                            const { fromParent } = this.props

                            window.presetVar.applicationForm_table = undefined
                            const { bodys, head, templetid } = window.presetVar.applicationForm_relate_data
                            const { pageCode, appcode, confirmRelate } = this.props
                            let userjson = {
                                pagecode: pageCode,
                                appcode: appcode,
                                addType: 'pull',

                                templateid: templetid,
                            }
                            head.pageid = fromParent === 'jkd' ? 'nc.vo.ep.bx.JKHeaderVO' : 'nc.vo.ep.bx.BXHeaderVO'
                            let data = {
                                userjson: JSON.stringify(userjson),
                                bodys, head,
                                pageid: pageCode
                            }


                            if (fromParent === 'jkd') {
                                requestApi.relateLoanInvoice({
                                    data: data,
                                    success: (data) => {
                                        const userjson_parse = JSON.parse(data.userjson) || {}
                                        console.log('userjson_parse===', userjson_parse)
                                        //存当前的是否无金额申请勾选
                                        window.presetVar.noAmountSq = userjson_parse.noAmountSq
                                        const { parentProps } = this.props
                                        parentProps.form.setAllFormValue({ [window.presetVar.head.head1]: data.head[window.presetVar.head.head1] })
                                        // const rows = parentProps.cardTable.getVisibleRows('jk_busitem')

                                        // let filterRows = rows.filter(item=>{
                                        //     return !(item.values.pk_item.value&&item.values.pk_mtapp_detail.value)
                                        // })

                                        // parentProps.cardTable.setTableData('jk_busitem', {rows:filterRows}, null, false)

                                        const resBody = Object.keys(data.bodys)
                                        const parentBody = window.presetVar.lsBodys
                                        parentBody.forEach(item => {
                                            if (!resBody.length || !resBody.some(item1 => item1 === item)) {
                                                parentProps.cardTable.setTableData(item, { areacode: item, rows: [] }, null, false)
                                            }
                                        })
                                        resBody.forEach((item) => {
                                            const newitemdata = data.bodys[item]
                                            if (newitemdata && newitemdata.rows) {
                                                const rows = []
                                                for (let i = 0; i < newitemdata.rows.length; i++) {

                                                    if (newitemdata.rows[i].values) {
                                                        rows[rows.length] = newitemdata.rows[i]
                                                    }
                                                }
                                                newitemdata.rows = rows
                                            }

                                            newitemdata && parentProps.cardTable.setTableData(item, newitemdata, null, false)
                                        })
                                        confirmRelate()
                                        window.presetVar.applicationForm_relate_data = undefined

                                    }
                                })
                            } else {
                                requestApi.relateInvoice({
                                    data: data,
                                    success: (data) => {

                                        const userjson_parse = JSON.parse(data.userjson) || {}
                                        console.log('userjson_parse===', data)
                                        //存当前的是否无金额申请勾选
                                        window.presetVar.noAmountSq = userjson_parse.noAmountSq
                                        const { parentProps, hideTables, confirmHide,parentbodys } = this.props

                                        if (userjson_parse) {
                                            if (userjson_parse.ISCONTRAST && userjson_parse.jkyjye && userjson_parse.jkyjye > 0) {//是否冲借款
                                                window.presetVar["ISCONTRAST"] = userjson_parse.ISCONTRAST;
                                            }else{
                                                window.presetVar["ISCONTRAST"] = "N";
                                            }
                                        }

                                        parentProps.form.setAllFormValue({ [window.presetVar.head.head1]: data.head[window.presetVar.head.head1] })
                                        // const rows =  parentProps.cardTable.getVisibleRows('arap_bxbusitem')

                                        // let filterRows = rows.filter(item=>{
                                        //     return !(item.values.pk_item.value&&item.values.pk_mtapp_detail.value)
                                        // })
                                        // parentProps.cardTable.setTableData('arap_bxbusitem', {rows:filterRows}, null, false)

                                        const resBody = Object.keys(data.bodys)
                                        const nomalHideTable = _.clone(window.presetVar.hideTables)
                                        nomalHideTable.forEach(item => {
                                            let index = hideTables.indexOf(item)
                                            if (resBody.indexOf(item) < 0) {
                                                if (index < 0) {
                                                    hideTables.push(item)
                                                }
                                                parentProps.cardTable.setTableData(item, { rows: [] }, null, false)
                                            } else {
                                                if (index > 0) {
                                                    hideTables.splice(index, 1)
                                                }
                                            }
                                        })
                                        confirmHide(hideTables)
                                       
                                        //重置hidetables
                                        // if(resBody.length){
                                            window.presetVar.lsBodys.forEach((item) => {
                                                if(resBody.indexOf(item)>-1){
                                                    const newitemdata = data.bodys[item]
                                                    if (newitemdata && newitemdata.rows) {
                                                        const rows = []
                                                        for (let i = 0; i < newitemdata.rows.length; i++) {
                            
                                                            if (newitemdata.rows[i].values) {
                                                                rows[rows.length] = newitemdata.rows[i]
                                                            }
                                                        }
                                                        newitemdata.rows = rows
                                                    }
                            
                                                    newitemdata && parentProps.cardTable.setTableData(item, newitemdata, null, false)
                                                }else{
                                                    parentProps.cardTable.setTableData(item,  { rows: [] }, null, false)
                                                }
                                               
                                            })
                                        // }else{
                                        //     window.presetVar.lsBodys.forEach(item=>{
                                        //         parentProps.cardTable.setTableData(item,  { rows: [] }, null, false)
                                        //     })
                                            
                                        // }
                                        confirmRelate()

                                    }
                                })
                            }
                        }
                    })
                }
            }
            size="sm"
        >{multiLang && multiLang.get('201103INUP-0045')}</NCButton> : ''
    }

    handleConfirmRelate() {
        let multiLang = this.props.MutiInit.getIntl(2011)
        const { fromParent } = this.props
        if (fromParent === 'jkd') {
            const _head = _.get(this.props.transferTable.getTransferTableAllSelectedId(), 'head.head', [])

            // console.log('查看选中===',window.presetVar.applicationForm_table)
            if (_head.length > 1) {
                //最多选择同一申请记录的不同数据!
                toast({
                    content: multiLang && multiLang.get('201102CZBX-0003'),
                    color: 'warning'
                });
                return;
            }
        }
        let ids = []
        const obj = _.get(this.props.transferTable.getTransferTableAllSelectedId(), 'head.body', [])
        for (let i in obj) {
            ids.push({
                bodys: obj[i].map(item => {
                    return { pk: item, ts: '' }
                }),
                head: {
                    pk: i, ts: ''
                }
            })
        }

        
        console.log('选中====', window.presetVar.applicationForm_table)
        const { head, templetid,bodys } = window.presetVar.applicationForm_relate_data
        const { pageCode, appcode, confirmRelate, parentbodys, parentProps } = this.props
        let userjson = {
            pagecode: pageCode,
            appcode: appcode,
            addType: 'pull',
            pulldata: ids,
            templateid: templetid,
        }

        head.pageid = fromParent === 'jkd' ? 'nc.vo.ep.bx.JKHeaderVO' : 'nc.vo.ep.bx.BXHeaderVO'
        let data = {
            userjson: JSON.stringify(userjson),
            bodys, head,
            pageid: pageCode
        }


        if (fromParent === 'jkd') {


            requestApi.relateLoanInvoice({
                data: data,
                success: (data) => {
                    //成功以后保存选中的项目
                    window.presetVar.applicationForm_table = this.props.transferTable.getTransferTableAllSelectedId()
                    const userjson_parse = JSON.parse(data.userjson) || {}
                    console.log('userjson_parse===', userjson_parse)
                    //存当前的是否无金额申请勾选
                    window.presetVar.noAmountSq = userjson_parse.noAmountSq
                    const { parentProps } = this.props
                    parentProps.form.setAllFormValue({ [window.presetVar.head.head1]: data.head[window.presetVar.head.head1] })
                    console.log('userjson_parse===', window.presetVar.lsBodys)
                    const resBody = Object.keys(data.bodys)
                    const parentBody = window.presetVar.lsBodys
                    parentBody.forEach(item => {
                        if (!resBody.length || !resBody.some(item1 => item1 === item)) {
                            parentProps.cardTable.setTableData(item, { areacode: item, rows: [] }, null, false)
                        }
                    })
                    resBody.forEach((item) => {
                        const newitemdata = data.bodys[item]
                        if (newitemdata && newitemdata.rows) {
                            const rows = []
                            for (let i = 0; i < newitemdata.rows.length; i++) {

                                if (newitemdata.rows[i].values) {
                                    rows[rows.length] = newitemdata.rows[i]
                                }
                            }
                            newitemdata.rows = rows
                        }

                        newitemdata && parentProps.cardTable.setTableData(item, newitemdata, null, false)
                    })
                    confirmRelate()
                }
            })
        } else {
            let bodyArr = Object.values(parentbodys);
            let billdata = parentProps.createExtCardData(pageCode, "head", bodyArr);
            billdata.userjson = JSON.stringify(userjson)
            billdata.pageid = pageCode

            requestApi.relateInvoice({
                data: billdata,
                success: (data) => {
                    //成功以后保存选中的项目
                    window.presetVar.applicationForm_table = this.props.transferTable.getTransferTableAllSelectedId()
                    const userjson_parse = JSON.parse(data.userjson) || {}


                    if (userjson_parse) {
                        if (userjson_parse.ISCONTRAST && userjson_parse.jkyjye && userjson_parse.jkyjye > 0) {//是否冲借款
                            window.presetVar["ISCONTRAST"] = userjson_parse.ISCONTRAST;
                        }else{
                            window.presetVar["ISCONTRAST"] = "N";
                        }
                    }

                    //存当前的是否无金额申请勾选
                    window.presetVar.noAmountSq = userjson_parse.noAmountSq
                    const { parentProps, hideTables, confirmHide } = this.props
                    parentProps.form.setAllFormValue({ [window.presetVar.head.head1]: data.head[window.presetVar.head.head1] })

                    const resBody = Object.keys(data.bodys)
                    const nomalHideTable = _.clone(window.presetVar.hideTables)
                    nomalHideTable.forEach(item => {
                        let index = hideTables.indexOf(item)
                        if (resBody.indexOf(item) < 0) {
                            if (index < 0) {
                                hideTables.push(item)
                            }
                            parentProps.cardTable.setTableData(item, { rows: [] }, null, false)
                        } else {
                            if (index > 0) {
                                hideTables.splice(index, 1)
                            }
                        }
                    })
                    confirmHide(hideTables)
                    //重置hidetables
                    window.presetVar.lsBodys.forEach((item) => {
                        if(resBody.indexOf(item)>-1){
                            const newitemdata = data.bodys[item]
                            if (newitemdata && newitemdata.rows) {
                                const rows = []
                                for (let i = 0; i < newitemdata.rows.length; i++) {
    
                                    if (newitemdata.rows[i].values) {
                                        rows[rows.length] = newitemdata.rows[i]
                                    }
                                }
                                newitemdata.rows = rows
                            }
    
                            newitemdata && parentProps.cardTable.setTableData(item, newitemdata, null, false)
                        }else{
                            parentProps.cardTable.setTableData(item,  { rows: [] }, null, false)
                        }
                       
                    })
                   
                    confirmRelate()
                }
            })
        }
    }
    beforeConfirm() {
        let multiLang = this.props.MutiInit.getIntl(2011)
        let flag = false
        if (window.presetVar.applicationForm_table && window.presetVar.applicationForm_table.head.head[0]) {
            let arr1 = [], arr2 = [];
            for (const i in window.presetVar.applicationForm_table.head.body) {
                arr1 = arr1.concat(window.presetVar.applicationForm_table.head.body[i])
            }
            let selectedBillObj = _.get(this.props.transferTable.getTransferTableAllSelectedId(), 'head', {})
            if (selectedBillObj.head && selectedBillObj.head[0]) {
                for (const i in selectedBillObj.body) {
                    arr2 = arr2.concat(selectedBillObj.body[i])
                }

                arr1.forEach(item => {
                    if (arr2.every(item1 => item1 !== item)) {
                        flag = true
                    }
                })
            } else {
                flag = true
            }

            if (flag) {
                promptBox({
                    color: 'warning',
                    title: multiLang && multiLang.get('201102JCLF_C-0002'),
                    content: multiLang && multiLang.get('201103INUP-0046'),
                    beSureBtnClick: () => {
                        this.handleConfirmRelate()
                    }
                })
            }
        }
        if (flag) {
            return
        }

        this.handleConfirmRelate()
    }
    render() {

        let { hide, button, table, editTable, search, transferTable, close, showApplicationFormModal } = this.props
        let { NCCreateSearch } = search;
        let { createButton } = button;
        let { createEditTable } = editTable;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let { createTransferTable } = transferTable;

        let isShowSelectedList = transferTable.getSelectedListDisplay(presetVar.areaCode.billsArea);
        let selectedBills = _.get(this.props.transferTable.getTransferTableAllSelectedId(), 'head.head', [])
        let canSave = selectedBills.length && selectedBills[0]
        return (
            <NCModal className='customModal' size="xlg" show={showApplicationFormModal}
                onHide={() => close()}
            >
                <NCModal.Header closeButton="true">
                    {/*"201102BCLF-0002": "冲借款",*/}
                    <NCModal.Title >{multiLang && multiLang.get('201102CZBX-0001')}</NCModal.Title>
                </NCModal.Header>


                <NCModal.Body>
                    <div><ProfileStyle
                        layout="singleTable"
                        {...this.props}
                    >
                        <ProfileBody>
                            {
                                isShowSelectedList ?
                                    null
                                    :
                                    <EmptyArea className="ssc-profile-search-area">

                                        {NCCreateSearch(
                                            presetVar.areaCode.searchArea,//模块id
                                            {
                                                clickPlanEve: searchClick.bind(this),//点击高级面板中的查询方案事件
                                                clickSearchBtn: searchClick.bind(this),//   点击按钮事件
                                                defaultConditionsNum: 1, //默认显示几个查询条件
                                                onAfterEvent: afterEvent()//编辑后事件
                                            }
                                        )}
                                    </EmptyArea>
                            }
                            <EmptyArea>
                                {createTransferTable(
                                    {
                                        headTableId: presetVar.areaCode.billsArea,//表格组件id
                                        bodyTableId: presetVar.areaCode.bodysArea,//子表模板id
                                        fullTableId: presetVar.areaCode.bodysArea,//主子拉平模板id
                                        //点击加号展开，设置表格数据cod
                                        // "201102CZBX-0002": "生成报销单"
                                        //transferBtnText: multiLang && multiLang.get('201102CZBX-0002'), //转单按钮显示文字
                                        transferBtnText: multiLang && multiLang.get('201103INUP-0044'),
                                        selectArea: this.selectArea.bind(this),
                                        containerSelector: '#transferSQToBx', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                                        cacheItem: [],
                                        showPagination: true,
                                        onPageInfoChange: searchClick.bind(this),
                                        showGenerateBtn: false,
                                        // dataSource: presetVar.dataSourceCode,
                                        onCheckedChange: (...res) => {

                                            const selectedArr = this.props.transferTable.getTransferTableAllSelectedId()
                                            const noAmountSq = this.props.search.getSearchValByField(presetVar.areaCode.searchArea, 'noamount')
                                            //设置无金额不可编辑
                                            if (selectedArr.head.head.length && selectedArr.head.head[0]) {
                                                const value = _.get(noAmountSq, 'value.firstvalue', false)
                                                this.props.search.setSearchValByField(presetVar.areaCode.searchArea, 'noamount', {
                                                    display: !!value,
                                                    value: !!value
                                                });
                                                this.props.search.setDisabledByField(presetVar.areaCode.searchArea, 'noamount', true);

                                            } else {
                                                this.props.search.setDisabledByField(presetVar.areaCode.searchArea, 'noamount', false);

                                            }
                                        },

                                        onChangeViewClick: () => {//点击切换视图钩子函数

                                            if (!this.props.meta.getMeta()[presetVar.areaCode.bodysArea]) {
                                                initTemplate(this.props); //加载主子拉平模板
                                            }
                                            this.props.transferTable.changeViewType(presetVar.areaCode.billsArea);

                                        }
                                    }
                                )}
                            </EmptyArea>
                        </ProfileBody>
                    </ProfileStyle>
                    </div>
                </NCModal.Body>
                <NCModal.Footer className="transfertableFooter">

                    <NCButton disabled={!canSave} colors='primary' onClick={() => this.beforeConfirm()}>
                        {multiLang && multiLang.get('201102BCLF-0017')}
                    </NCButton>
                    <NCButton onClick={() => close()}>
                        {multiLang && multiLang.get('201102BCLF-0018')}
                    </NCButton>
                </NCModal.Footer>
            </NCModal>

        )
    }
}
export default createPage({ mutiLangCode: '2011' })(ExpenseaccountForPull)

// ExpenseaccountForPull = createPage({
//     mutiLangCode: '2011'
// })(ExpenseaccountForPull);


// const routes = [
// 	{
// 		path: '/pull',
// 		component: ExpenseaccountForPull
//     },
//     {
//         path: '/card',
//         component: expenseaccountCard
//     }
// ];


// (function main(routers,htmlTagid){
//   RenderRouter(routers,htmlTagid);
// })(routes,"app");

//ReactDOM.render(<ExpenseaccountForPull />, document.querySelector('#app'));